package com.chb.appGateway.filter;

import com.alibaba.fastjson2.JSON;
import com.chb.appGateway.white.UrlPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: 陈海彬
 * @date: Created in 2023/12/8 8:54
 * @description: 登录过滤器
 * @modified By:
 * @version: 1.0
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private UrlPath urlPath;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1.获取客户的请求路径
        String path = request.getPath().toString();
        // 判断请求路径是否在白名单
        if (urlPath.getPath().contains(path)) {
            return chain.filter(exchange);
        }
        // 3获取请求的token
        String token = request.getHeaders().getFirst("token");
        // 4.检验token是否合法，redis和jwt
        Boolean flag = redisTemplate.hasKey("user:" + token);
        if (flag) {
            ValueOperations<String, String> forValue = redisTemplate.opsForValue();
            // token的令牌刷新机制
            forValue.set("user:" + token, forValue.get("user:" + token), 30, TimeUnit.MINUTES);
            return chain.filter(exchange);
        }
        // 5.响应一个JSON数据
        Map<String, Object> map = new HashMap<>();
        map.put("message", "未登录");
        map.put("code", 403);
        byte[] bytes = JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8);
        // 5.1调用bufferFactory方法，生成DataBuff对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        // 5.2调用Mono中的just方法，返回要写给前端的数据
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 返回值越大优先级越低
     */
    @Override
    public int getOrder() {
        return 0;
    }


}